package com.java.base.lock;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
import org.openjdk.jol.vm.VirtualMachine;

public class ObjectBiasedLock {


    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> test1(1000)).start();
        new Thread(() -> test1(2000)).start();
//        new Thread(() -> test1(3000)).start();
    }


    static volatile LockObj obj = new LockObj();

    public static Object test1(int t) {

        System.out.println("========加锁前========");
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        synchronized (obj) {

            try {
                Thread.sleep(t);
            } catch (InterruptedException e) {
            }

            System.out.println("========加锁后========");
            System.out.println(ClassLayout.parseInstance(obj).toPrintable());
            System.out.println(obj.hashCode());
        }

        System.out.println("========解锁后========");
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        return obj;
    }

    public static Object test() {

        System.out.println("========加锁前========");
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        synchronized (obj) {
            System.out.println("========加锁后========");
            System.out.println(ClassLayout.parseInstance(obj).toPrintable());
            System.out.println(obj.hashCode());
        }

        System.out.println("========解锁后========");
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        return obj;
    }


    public static void test2(Object obj) {

        ClassLayout classLayout = ClassLayout.parseInstance(obj);
        System.out.println(classLayout.toPrintable());
//        for (FieldLayout fieldLayout : classLayout.fields()) {
//            System.out.println(fieldLayout.name());
//        }
        VirtualMachine vm = VM.current();
        int i = vm.getInt(obj, 4);
        System.out.println(Integer.toBinaryString(i));

    }


    private static class LockObj {

    }
}

